package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.Album;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;

public class AlbumAdd extends HttpServlet {
	@Override
	public void init() throws ServletException {	
	}
	@Override
	public void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		try {
			  request.setCharacterEncoding("utf-8");
			  response.setCharacterEncoding("utf-8");
			  response.setContentType("text/html;charset=utf-8");
			  
			  AlbumDao albumDao = AlbumDao.getDao();
			  Album album = new Album();
			  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
				if (!isMultipart) {
					System.out.println("File Not Uploaded");
				} else {
					FileItemFactory factory = new DiskFileItemFactory();
					ServletFileUpload upload = new ServletFileUpload(factory);
				    List<?> items = null;
				    try {
					items = upload.parseRequest(request);
					} catch (FileUploadException e) {
					e.printStackTrace();
					}
					Iterator<?> itr = items.iterator();
					while (itr.hasNext()) {		    
					FileItem item = (FileItem) itr.next();
					
							  if(item.getFieldName().equals("picName")){
								  album.setName(item.getString(request.getCharacterEncoding())); 							  
							  if(itr.hasNext()){  
								  FileItem itemPic = (FileItem) itr.next();
								  if (!itemPic.isFormField()){
									  if(itemPic.getName()!=null&&itemPic.getName()!="")
									  {
									  String itemName = FilenameUtils.getName(itemPic.getName());
									  
									  Random generator = new Random();
									  int r = Math.abs(generator.nextInt());

									  String reg = "[.*]";
									  String replacingtext = "";
									  
									  Pattern pattern = Pattern.compile(reg);
									  Matcher matcher = pattern.matcher(itemName);
									  StringBuffer buffer = new StringBuffer();

									  while (matcher.find()) {
									  matcher.appendReplacement(buffer, replacingtext);
									  }
									  int IndexOf = itemName.indexOf("."); 
									  String preFileName = itemName.substring(IndexOf);
									  /*System.out.println("preFileName: "+preFileName);
						              System.out.println("fileName:" + buffer.toString());
						              System.out.println("fileType:" + item.getContentType());
						              System.out.println("fileSize:" + item.getSize() + "byte");*/
									  String finalimage = buffer.toString()+"_"+r+preFileName;
									  System.out.println("Final Image==="+finalimage);
									  String path = getServletContext().getRealPath("/");
									  Properties pro = System.getProperties();
								         String osName = pro.getProperty("os.name");
								         File saveFile = null;
								         String savePath = null;
								         String relativeSavePath = null;
								         
								         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
								        	 savePath = path+"/pictures/"+finalimage;
								        	 saveFile = new File(savePath); 
								        	
								         }
								         else{
								        	 savePath = path+"pictures\\"+finalimage;
								        	 saveFile = new File(savePath);
								         }
								         relativeSavePath = "pictures/"+finalimage;
									  itemPic.write(saveFile);
									  album.setCoverPicAddress(relativeSavePath);
								  }
							  }
							  }
			  LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			  album.setLeagueId(luSessionCookieAccess.getLeagueId());
			  albumDao.addAlbum(album);
			  response.sendRedirect("./albums.jsp?league="+luSessionCookieAccess.getLeagueId());
							  }
					}
				}
		} catch (Exception e) {
			e.printStackTrace();
			sendInternalError(response);
			return;
		}
	}
	
	private void sendInternalError(HttpServletResponse httpResponse)
			throws IOException {
		httpResponse.sendError(500, "数据库读取错误");
	}
}
